<template>
  <div class="container">
    <!-- 顶部导航栏 -->
    <transition name="slide">
      <van-nav-bar left-arrow :fixed="true" @click-left="onClickLeft" v-show="show">
        <template #title>
          {{ currentChapterName }}
        </template>
        <template #right>
          <p class="all" @click="gotoComicCover">全集</p> <van-icon name="share-o" size="18" />
        </template>
      </van-nav-bar>
    </transition>
    <van-loading size="40" v-if="loadingMore" class="loadingMore" />
    <!-- 这里是漫画内容 容器 -->
    <div class="content" @click="toggleShow" ref="contentRef">
      <!-- 这里是漫画内容 -->
      <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" class="list"
        :immediate-check="false" @scroll.passive="handleScroll" :style="{ overflowY: 'visible' }">
        <ul v-for="chapterContent in chapterContents" :key="chapterContent.id" :data-chapter-name="chapterContent.name"
          :id="'chapter-' + chapterContent.id">
          <li v-for="(pic, index) in chapterContent.piclist" :key="index" :data-chapter-id="chapterContent.id"
            :data-last-pic="index === chapterContent.piclist.length - 1">
            <van-image :src="getProxyImageUrl(pic.url)" />
          </li>
        </ul>
      </van-list>
    </div>
  </div>
  <contentTabBar :show="show" :chapterInfoList="chapterInfoList" @change-show="changeShow"
    @change-chapter-id="changeChapterId" />
</template>
<script setup>
import { throttle } from 'lodash';
import { getProxyImageUrl } from "@/util/index.js";
import { getComicChapters, getChapterListDetail } from "@/api/index.js";
import { ref, onMounted, computed, watch, useTemplateRef, nextTick, onUnmounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useStore } from "@/stores/index.js";
const store = useStore();
const router = useRouter();
const route = useRoute();
// 数据初始化
const comicId = computed(() => route.params.id); // 漫画ID
const chapterInfoList = ref([]); // 章节信息列表
const chapterContents = ref([]); // 当前章节内容
const loading = ref(false); // 是否正在加载
const finished = ref(false); // 是否已经加载完毕
const show = ref(true); // 是否显示顶部导航栏和底部菜单
const contentRef = useTemplateRef('contentRef'); // 引用 content 元素
const isHandlingScroll = ref(false); // 防止滚动事件重复触发
const loadingMore = ref(false); // 是否正在加载更多
let previousScrollTop = null;
// 计算属性
const currentChapterIndex = computed(() => store.currentChapterIndex); // 当前章节索引
const currentChapterId = computed(() => chapterInfoList.value[currentChapterIndex.value]?.id); // 当前章节ID
const currentChapterName = computed(() => {
  return chapterInfoList.value[currentChapterIndex.value]?.name || "未知章节";
}); // 当前章节名称

// 修改章节切换方法
const changeChapterId = async (chapterId) => {
  const targetIndex = chapterInfoList.value.findIndex((chapter) => chapter.id === chapterId);
  if (targetIndex === -1) return;

  // 保留相邻章节避免清空
  const keepChapters = chapterContents.value.filter(c => {
    const idx = chapterInfoList.value.findIndex(ci => ci.id === c.id);
    return Math.abs(idx - targetIndex) <= 1;
  });

  chapterContents.value = keepChapters;
  store.setCurrentChapterIndex(targetIndex);

  // 确保目标章节已加载
  if (!chapterContents.value.some(c => c.id === chapterId)) {
    await loadChapterContent(chapterId);
  }

  // 预加载相邻章节
  [targetIndex - 1, targetIndex + 1].forEach(async (idx) => {
    if (idx >= 0 && idx < chapterInfoList.value.length) {
      await loadChapterContent(chapterInfoList.value[idx].id);
    }
  });

  // 等待DOM更新后滚动定位
  await nextTick();
  const chapterEl = document.getElementById(`chapter-${chapterId}`);
  if (chapterEl) {
    contentRef.value.scrollTop = chapterEl.offsetTop;
    previousScrollTop = chapterEl.offsetTop;
  }
};




// 加载章节内容
const loadChapterContent = async (chapterId) => {
  try {
    loading.value = true;
    if (chapterContents.value.some((content) => content.id === chapterId)) return;

    const res = await getChapterListDetail(chapterId);
    const targetIndex = chapterInfoList.value.findIndex(c => c.id === chapterId);

    // 查找正确的插入位置
    let insertIndex = chapterContents.value.findIndex(c => {
      return chapterInfoList.value.findIndex(ci => ci.id === c.id) > targetIndex
    });

    if (insertIndex === -1) insertIndex = chapterContents.value.length;
    chapterContents.value.splice(insertIndex, 0, res.data);

  } finally {
    loading.value = false;
    await nextTick();
  }
};

// 强化章节定位检测
const checkCurrentChapter = () => {
  const scrollPosition = contentRef.value.scrollTop + contentRef.value.clientHeight * 0.4;
  let closestChapter = null;
  let minDistance = Infinity;

  chapterContents.value.forEach(chapter => {
    const chapterEl = document.getElementById(`chapter-${chapter.id}`);
    if (chapterEl) {
      const chapterTop = chapterEl.offsetTop;
      const chapterBottom = chapterTop + chapterEl.offsetHeight;

      // 计算章节中间点与滚动位置的接近程度
      const chapterCenter = (chapterTop + chapterBottom) / 2;
      const distance = Math.abs(scrollPosition - chapterCenter);

      if (distance < minDistance) {
        minDistance = distance;
        closestChapter = chapter;
      }
    }
  });

  if (closestChapter) {
    const newIndex = chapterInfoList.value.findIndex(c => c.id === closestChapter.id);
    if (newIndex !== -1 && newIndex !== currentChapterIndex.value) {
      store.setCurrentChapterIndex(newIndex);
    }
  }
};

// 页面加载时初始化数据
onMounted(async () => {
  if (contentRef.value) {
    contentRef.value.addEventListener('scroll', handleScroll);
  }
  const resChapters = await getComicChapters(comicId.value);
  chapterInfoList.value = resChapters.data.map((chapter) => ({
    id: chapter.id,
    name: chapter.name,
    chapter: chapter.chapter,
    sort: chapter.sort,
  }));
  store.setChapterInfoList(chapterInfoList.value);
  // 默认加载当前章节
  await loadChapterContent(currentChapterId.value);
  // 确保 DOM 渲染完成
  await nextTick();
  // 初始化 previousScrollTop
  previousScrollTop = contentRef.value.scrollTop;

  // 滚动到当前章节的位置
  const currentChapterElement = document.getElementById(`chapter-${currentChapterId.value}`);
  if (currentChapterElement) {
    currentChapterElement.scrollIntoView({ behavior: 'auto' });
    previousScrollTop = contentRef.value.scrollTop; // 更新滚动位置
  }
});

// 优化滚动处理逻辑
const handleScroll = throttle(async () => {
  if (!contentRef.value || finished.value || isHandlingScroll.value) return;
  isHandlingScroll.value = true;

  try {
    const scrollContainer = contentRef.value;
    const currentScrollTop = scrollContainer.scrollTop;
    // 动态检测当前章节
    checkCurrentChapter();
    if (previousScrollTop !== null) {
      const direction = currentScrollTop > previousScrollTop ? 'down' : 'up';
      const currentChapterEl = document.getElementById(`chapter-${currentChapterId.value}`);
      if (!currentChapterEl) return;
      // 处理向下滚动（加载下一章）
      if (direction === 'down') {
        const lastPic = currentChapterEl.querySelector('[data-last-pic="true"]');
        if (lastPic) {
          const rect = lastPic.getBoundingClientRect();
          if (rect.bottom <= window.innerHeight + 100) {
            const nextIndex = currentChapterIndex.value + 1;
            if (nextIndex < chapterInfoList.value.length) {
              const nextId = chapterInfoList.value[nextIndex].id;
              if (!chapterContents.value.some(c => c.id === nextId)) {
                await loadChapterContent(nextId);
                // 自动更新当前章节索引
                store.setCurrentChapterIndex(nextIndex);
              }
            }
          }
        }
      }
      // 处理向上滚动（加载上一章）
      else {
        const firstPic = currentChapterEl.querySelector('li:first-child');
        if (firstPic) {
          const rect = firstPic.getBoundingClientRect();
          if (rect.top <= 50) {
            const prevIndex = currentChapterIndex.value - 1;
            if (prevIndex >= 0) {
              const prevId = chapterInfoList.value[prevIndex].id;
              if (!chapterContents.value.some(c => c.id === prevId)) {
                // 记录当前滚动位置
                const prevScroll = scrollContainer.scrollTop;

                await loadChapterContent(prevId);
                await nextTick();

                // 计算位置偏移量
                const newChapterEl = document.getElementById(`chapter-${prevId}`);
                if (newChapterEl) {
                  // 保持视觉连续性
                  scrollContainer.scrollTop = prevScroll + newChapterEl.offsetHeight;
                }
                // 更新章节索引
                store.setCurrentChapterIndex(prevIndex);
              }
            }
          }
        }
      }
    }
    previousScrollTop = currentScrollTop;
  } finally {
    isHandlingScroll.value = false;
  }
}, 100);



// 解绑滚动事件
onUnmounted(() => {
  if (contentRef.value) {
    contentRef.value.removeEventListener('scroll', handleScroll);
  }
});
// 切换顶部导航栏和底部菜单显示状态
const toggleShow = () => {
  show.value = !show.value;
};
// 返回上一页
const onClickLeft = () => {
  router.go(-1);
};
// 查看全集
const gotoComicCover = () => {
  router.push({ path: `/comicCover/${comicId.value}` })
};

</script>
<style scoped>
.container {
  width: 100vw;
  height: 100vh;
  overflow: visible;
  /* 确保不阻止子元素的滚动 */
  position: relative;
}

.all {
  margin-right: 15px;
}

.content {
  width: 100vw;
  height: calc(100vh - 50px);
  /* 减去顶部导航栏的高度 */
  overflow-x: hidden;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}

.list {
  height: 100%;
  overflow-y: visible;
}

.list::-webkit-scrollbar {
  display: none;
}

ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

li {
  width: 100vw;
  height: auto;
  display: block;
}

img {
  width: 100%;
  height: auto;
  display: block;
}

/* 定义滑动动画 */
.slide-enter-active,
.slide-leave-active {
  transition: transform 0.5s ease;
}

.slide-enter-from {
  transform: translateY(-100%);
}

.slide-enter-to {
  transform: translateY(0);
}

.slide-leave-from {
  transform: translateY(0);
}

.slide-leave-to {
  transform: translateY(-100%);
}

.loadingMore {
  position: relative;
  width: 100vw;
  height: 100vh;
  background: #fff;
  z-index: 99;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
